from flask import Blueprint, render_template, \
    current_app, request, flash, redirect, url_for
from flask_login import login_required, current_user
from app.models.user import User
from app.forms.user import UserForm, UserUpdateForm
from app.extensions import db

bp = Blueprint('users', __name__)


@bp.before_request
@login_required
def before_request():
    pass


@bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    pre_page = current_app.config['POST_PRE_PAGE']
    query = User.query.order_by(User.id.desc())
    pagination = query.paginate(page, pre_page)
    return render_template('admin/users/index.html',
                           model=pagination.items,
                           page=page,
                           pagination=pagination)


@bp.route('/create', methods=['GET', 'POST'])
def create():
    form = UserForm()
    model = User()
    if model.save(form):
        flash('添加用户成功', 'success')
        return redirect(url_for('users.index'))
    return render_template('admin/users/create.html', form=form)


@bp.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    form = UserUpdateForm()
    model = User.query.get_or_404(id)
    if form.validate_on_submit():
        with db.auto_commit():
            if form.nickname.data:
                model.nickname = form.nickname.data
            model.password = form.new_password.data
            flash('更新成功', 'success')
            return redirect(url_for('users.index'))
    form.load(model)
    return render_template('admin/users/update.html', form=form)


@bp.route('/delete/<int:id>')
def delete(id):
    user = User.query.get_or_404(id)
    if user == current_user:
        flash('不能删除自身!', 'danger')
        return redirect(request.referrer or url_for('user.index'))

    user.delete(True)
    flash('删除成功!', 'success')
    return redirect(url_for('users.index'))
